package c.x.jy.common.mqtt;

import java.util.concurrent.ScheduledExecutorService;

import javax.net.SocketFactory;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttConsumer {
	// public static final String HOST = "tcp://127.0.0.1:61613";
	// public static final String TOPIC1 = "pos_message_all";
	// private static final String clientid = "client11";
	// public static final String HOST = "tcp://10.95.197.1:1883";
	//public static final String HOST = "tcp://47.112.194.147:1883";
	public static final String HOST = "tcp://www.dianduoke.com:1883";
	public static final String TOPIC1 = "JYTopic/server";
	private static final String clientid1 = "jiayuan";
	private static MqttClient client;
	private MqttConnectOptions options;
	private String userName = "ddk"; // 非必须
	private String passWord = "888888"; // 非必须
	@SuppressWarnings("unused")
	private ScheduledExecutorService scheduler;
	private String sslPemPath = "E:\\2018\\IOT\\MQTT\\javassl\\java\\";

	private void start() {
		try {
			// host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
			client = new MqttClient(HOST, clientid1, new MemoryPersistence());
			// MQTT的连接设置
			options = new MqttConnectOptions();
			// -----------SSL begin--------------
			// SSLSocketFactory factory =
			// HttpUtil.createSSLConnectionSocketFactory(null, null);// =
			// OpensslHelper.getSSLSocktet(sslPemPath + "sccCA0.crt",sslPemPath
			// +"sccDevSMP.crt",sslPemPath + "sccDevSMP.key","shihuc");
			options.setSocketFactory(SocketFactory.getDefault());
			// -----------end of SSL ------------
			// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
			options.setCleanSession(true);
			// 设置连接的用户名
			options.setUserName(userName);
			// 设置连接的密码
			  options.setPassword(passWord.toCharArray());
			// 设置超时时间 单位为秒
			options.setConnectionTimeout(10);
			// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
			options.setKeepAliveInterval(20);
			// 设置重连机制
			options.setAutomaticReconnect(true);
			// 设置回调
			client.setCallback(new PushCallback());
			MqttTopic topic = client.getTopic(TOPIC1);
			// setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
			// options.setWill(topic, "close".getBytes(), 2, true);//遗嘱
			client.connect(options);

			// 订阅消息
			int[] Qos = { 1 };
			String[] topic1 = { TOPIC1 };
			client.subscribe(topic1, Qos);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 用来连接服务器
	 */
	private static MqttTopic connect(String topic) {
		MqttConnectOptions options = new MqttConnectOptions();
		options.setCleanSession(false);
		// options.setUserName(userName);
		// options.setPassword(passWord.toCharArray());
		// 设置超时时间
		options.setConnectionTimeout(10);
		// 设置会话心跳时间
		options.setKeepAliveInterval(20);
		try {
			if (client == null)
				client = new MqttClient(HOST, clientid1, new MemoryPersistence());
			client.setCallback(new PushCallback());
			client.connect(options);

			MqttTopic topic11 = client.getTopic(topic);
			return topic11;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void sendMessage(String clieId, String msg,String topic) throws Exception {
		// ServerMQTT server = new ServerMQTT();
		MqttMessage message = new MqttMessage();
		message.setQos(1); // 保证消息能到达一次
		message.setRetained(true);
		String str = "{\"clieId\":\"" + clieId + "\",\"mag\":\"" + msg + "\"}";
		message.setPayload(str.getBytes());
		try {
			// publish(server.topic11 , server.message);

			MqttDeliveryToken token = connect(topic).publish(message);

			token.waitForCompletion();
			System.out.println("message is published completely! " + token.isComplete());
			// 断开连接
			// server.client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 启动入口
	 * 
	 * @param args
	 * @throws Exception
	 */

	public static void main(String[] args) throws Exception {
		System.setProperty("javax.net.debug", "ssl,handshake");
	   MqttConsumer client = new MqttConsumer();
   client.start();
 
	 	sendMessage("123444", "哈哈","JYTopic/server");
	}
}

class PushCallback implements MqttCallback {

	@Override
	public void connectionLost(Throwable cause) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		// TODO Auto-generated method stub
		
	}
	
	
}